package com.hy.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hy.reggie.current.R;
import com.hy.reggie.dto.DishDto;
import com.hy.reggie.dto.SetmealDto;
import com.hy.reggie.pojo.Category;
import com.hy.reggie.pojo.Dish;
import com.hy.reggie.pojo.Setmeal;
import com.hy.reggie.pojo.SetmealDish;
import com.hy.reggie.service.CategoryService;
import com.hy.reggie.service.SetmealDishService;
import com.hy.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;


    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> add(@RequestBody SetmealDto setmealDto) {
        log.info("新增套餐：{}", setmealDto.toString());

        setmealService.add(setmealDto);

        return R.success("添加成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<SetmealDto>> page(int page, int pageSize, String name) {

        //原始分页构造器
        Page<Setmeal> setmealPage = new Page<>(page, pageSize);
        //响应的分页构造器
        Page<SetmealDto> setmealDtoPage = new Page<>(page, pageSize);

        //条件构造器
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.like(name != null, Setmeal::getName, name);
        setmealLambdaQueryWrapper.orderByDesc(Setmeal::getUpdateTime);

//        获取setmeal表中的记录
        List<Setmeal> records = setmealService.page(setmealPage,setmealLambdaQueryWrapper).getRecords();

        //将原始分页构造器的内容复制到响应的分页构造器
        BeanUtils.copyProperties(setmealPage, setmealDtoPage, "records");

        //item：查询到的每条记录，Setmeal类型
        List<SetmealDto> setmealDtoList = records.stream().map((item) -> {
            SetmealDto setmealDto = new SetmealDto();
//            将保留数据复制到dto中
            BeanUtils.copyProperties(item, setmealDto);

            //获取套餐及菜品分类id
            Long id = item.getCategoryId();

            //根据id查询到对应的category信息
            Category category = categoryService.getById(id);

            if (category != null) {
                //获得类型名字
                String categoryName = category.getName();
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        //设置响应分页构造器的记录
        setmealDtoPage.setRecords(setmealDtoList);

        return R.success(setmealDtoPage);
    }

    /**
     * 根据id查询菜品
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<SetmealDto> selectOne(@PathVariable Long id) {
        SetmealDto setmealDto = setmealService.selectOne(id);

//        log.info(dishDto.toString());

        return R.success(setmealDto);
    }

    @PutMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto) {

        setmealService.updateSetmealAndDish(setmealDto);

        return R.success("修改成功");
    }

    /**
     * 修改菜品售卖状态
     * @param status
     * @param ids
     * @return
     */
    @PostMapping("/status/{status}")
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> updateStatus(@PathVariable int status, String ids) {
        log.info("修改菜品售卖状态：{}", ids);

        String[] split = ids.split(",");

        for (int i = 0; i < split.length; i++) {
            Setmeal setmeal = setmealService.getById(split[i]);
            setmeal.setStatus(status);
            setmealService.updateById(setmeal);
        }

        return R.success("修改成功");
    }

    /**
     * 删除菜品
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "setmealCache",allEntries = true)
    public R<String> delete(String ids) {
        log.info("删除菜品：{}", ids);

        String[] split = ids.split(",");

        LambdaQueryWrapper<SetmealDish> setmealDishServiceLambdaQueryWrapper = new LambdaQueryWrapper<>();

        //检查套餐是否停售
        for (String id : split) {
            if (setmealService.getById(id).getStatus() == 1) {
                return R.error("不能删除正在售卖的套餐");
            }
        }

        for (String id : split) {
            setmealDishServiceLambdaQueryWrapper.eq(SetmealDish::getSetmealId, id);
            System.out.println(id);
            setmealDishService.remove(setmealDishServiceLambdaQueryWrapper);
        }

        setmealService.removeByIds(Arrays.asList(split));

        return R.success("删除成功");
    }

    /**
     * 根据条件查询套餐数据
     * http://localhost:8080/setmeal/list?categoryId=1413342269393674242&status=1
     *
     * @param setmeal
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "setmealCache",key = "'setmeal_'+#setmeal.categoryId+'_'+#setmeal.status")
    public R<List<Setmeal>> list(Setmeal setmeal) {

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId());

        queryWrapper.eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());

        queryWrapper.orderByDesc(Setmeal::getUpdateTime);

        List<Setmeal> list = setmealService.list(queryWrapper);

        return R.success(list);

    }

}
